<template>
  <div class="flex px-2 py-2 h-[100%] ai-toolbox">
    <el-card class="w-[40%]" shadow="never">
      <toolbar
        ref="toolbarRef"
        :isStreaming="isStreaming"
        @search="handleSubmit"
        @clear="handleClear"
      ></toolbar>
    </el-card>
    <el-card class="w-[60%]" shadow="never">
      <template #header>
        <div class="flex justify-between">
          <div class="flex items-center">
            <img class="w-[52px] h-[30px]" src="@/assets/images/ai.png" />
            <span class="ml-2 mr-2">生成结果</span>
            <div class="progress-container" v-show="isStreaming">
              <div class="square"></div>
              <div class="square"></div>
              <div class="square"></div>
              <div class="square"></div>
              <div class="square"></div>
              <div class="square"></div>
              <div class="square"></div>
            </div>
          </div>

          <div>
            <!-- <el-tooltip
              class="box-item"
              effect="dark"
              content="停止生成"
              placement="top-start"
            >
              <i
                style="font-size: 14px !important"
                class="dk-iconfont icon-bofang cursor-pointer ml-[8px] text-[#999999]"
                @click="hanldeStop"
                v-if="isStreaming"
              />
            </el-tooltip> -->
            <el-tooltip
              class="box-item"
              effect="dark"
              content="清空"
              placement="top-start"
            >
              <i
                v-if="!isStreaming && content"
                style="font-size: 14px !important"
                class="dk-iconfont icon-Clear cursor-pointer ml-[8px] text-[#999999]"
                @click="handleClear"
              />
            </el-tooltip>
            <el-tooltip
              class="box-item"
              effect="dark"
              content="复制"
              placement="top-start"
            >
              <i
                style="font-size: 14px !important"
                class="dk-iconfont icon-Copy cursor-pointer ml-[8px] text-[#999999]"
                @click="copyToClipboard"
                v-if="!isStreaming && content"
              />
            </el-tooltip>
          </div>
        </div>
      </template>
      <MarkdownRender ref="MarkdownRenderRef" :content="content"></MarkdownRender>
      <div class="base-red-color text-xs">注：内容来源于所选大模型分析，仅供参考</div>
    </el-card>
  </div>
</template>
<script name="Ai-toolboxIndex" setup lang="jsx">
import toolbar from "./components/toolbar.vue";
import MarkdownRender from "./components/MarkdownRender.vue";
import { fast_gptStream, setToken } from "./deepseek.js";
import { getToken } from "./api";
import { ElMessage, ElMessageBox } from "element-plus";

const data = reactive({
  content: "",
  isStreaming: false,
});

const MarkdownRenderRef = ref();
const toolbarRef = ref();

const { content, isStreaming } = toRefs(data);

let streamController = ref(null);
// 请求
const handleSubmit = async (data) => {
  isStreaming.value = true;
  try {
    if (content.value) {
      content.value += "<p style='border: 1px solid #eff3fe;margin: 10px 0'></p>"; // 使用 Markdown 分割线
    }
    streamController.value = await fast_gptStream(
      data.model_type,
      data.userText,
      onDataChunk,
      onComplete
    );
  } catch (e) {
    console.warn(e);
  }
};

const onDataChunk = (chunk) => {
  content.value += chunk;
};

const onComplete = () => {
  isStreaming.value = false;
};

// 复制
const copyToClipboard = async () => {
  try {
    // 过滤掉特定的HTML标签
    const filteredContent = content.value.replace(
      /<p style='border: 1px solid #eff3fe;margin: 10px 0'><\/p>/g,
      ""
    );
    // 检查是否支持 navigator.clipboard
    if (navigator.clipboard && navigator.clipboard.writeText) {
      await navigator.clipboard.writeText(filteredContent);
      ElMessage.success("内容已复制到剪贴板");
    } else {
      // 回退方案：使用 document.execCommand('copy')
      fallbackCopyTextToClipboard(filteredContent);
    }
  } catch (err) {
    console.error("复制失败", err);
    ElMessage.error("复制失败，请手动复制");
  }
};

const fallbackCopyTextToClipboard = (text) => {
  const textArea = document.createElement("textarea");
  textArea.value = text;
  document.body.appendChild(textArea);
  textArea.focus();
  textArea.select();

  try {
    document.execCommand("copy");
    ElMessage.success("内容已复制到剪贴板");
  } catch (err) {
    console.error("复制失败", err);
    ElMessage.error("复制失败，请手动复制");
  }

  document.body.removeChild(textArea);
};

// 清空内容
const handleClear = () => {
  content.value = "";
};

// 停止生成
const hanldeStop = () => {
  console.log(streamController.value);

  if (streamController.value) {
    streamController.value.stop();
    streamController.value = null;
  }
  isStreaming.value = false;
};

const getTokenApi = async () => {
  const res = await getToken();
  setToken(atob(res.data));
};

onMounted(() => {
  getTokenApi();
});
</script>
<style lang="scss" scoped>
:deep(.el-card__body) {
  padding: 0 24px;
}
.ai-toolbox {
  &:deep(.el-form-item__label) {
    margin-bottom: 2px !important;
  }
  .tool {
    flex-grow: 1;
  }
  .content {
    flex-grow: 1;
  }
  // }
}

.progress-container {
  display: flex;
  gap: 8px;
  // padding: 20px;
}

.square {
  width: 20px;
  height: 20px;
  background: #ddd;
  position: relative;
  animation: colorWave 1.6s ease-in-out infinite;
}

/* 为每个方块设置不同的动画延迟 */
.square:nth-child(1) {
  animation-delay: 0s;
}
.square:nth-child(2) {
  animation-delay: 0.2s;
}
.square:nth-child(3) {
  animation-delay: 0.4s;
}
.square:nth-child(4) {
  animation-delay: 0.6s;
}
.square:nth-child(5) {
  animation-delay: 0.8s;
}
.square:nth-child(6) {
  animation-delay: 1s;
}
.square:nth-child(7) {
  animation-delay: 1.2s;
}

@keyframes colorWave {
  0%,
  100% {
    background-color: #ddd;
    transform: scale(1);
  }
  50% {
    background-color: #3487ff;
    transform: scale(1.1);
  }
}

/* 可选：添加流动光效的高级版本 */
.square::after {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(
    90deg,
    rgba(255, 255, 255, 0) 0%,
    rgba(255, 255, 255, 0.3) 50%,
    rgba(255, 255, 255, 0) 100%
  );
  opacity: 0;
  animation: shine 1.6s ease-in-out infinite;
}

@keyframes shine {
  0% {
    opacity: 0;
    left: -100%;
  }
  50% {
    opacity: 1;
  }
  100% {
    opacity: 0;
    left: 100%;
  }
}
</style>
